package leetcode;

import java.util.Arrays;

public class LeetCode91 {

    int n;

    String s;

    int count;

    //回溯法
    public int numDecodings1(String s) {
        this.n = s.length();
        this.s = s;
        helper(0);
        return count;
    }

    private void helper(int index) {
        if (index == n)
            count++;
        else if (index > n)
            return;
        else if (n - index > 2) {
            int num = Integer.parseInt(s.substring(index, index + 2));
            if (num >= 0 && num < 26)
                helper(index + 2);
        }
        helper(index + 1);
    }
//------------------------------------------------------------------

    public int numDecodings2(String s) {
        int length = s.length();
        int[] dp = new int[length];
        dp[0] = Integer.parseInt(s.substring(0, 2)) <= 26 ? 2 : 1;
        for (int i = 1; i < length; i++) {
            if (i + 2 <= length && Integer.parseInt(s.substring(i, i + 2)) <= 26)
                dp[i] = dp[i - 1] * 2;
            else
                dp[i] = dp[i - 1];
        }
        return dp[length - 1];
    }

    public static void main(String[] args) {
        LeetCode91 leetCode91 = new LeetCode91();
        System.out.println(leetCode91.numDecodings("226"));
    }

    public int numDecodings3(String s) {
        int num = s.substring(0, 1).equals("0") ? 0 : 1;
        if (s.length() == 1)
            return num;
        int length = s.length();
        int[] dp = new int[length];
        dp[0] = num;
        dp[1] = Integer.parseInt(s.substring(0, 2)) <= 26 ? dp[0] + 1 : 1;
        if (s.substring(1, 2).equals("0"))
            dp[1] -= 1;
        int tmp;
        for (int i = 2; i < length; i++) {
            tmp = Integer.parseInt(s.substring(i - 1, i + 1)) <= 26 ? dp[i - 2] : 0;
            if (s.substring(i, i + 1).equals("0"))
                dp[i] = tmp;
            else
                dp[i] = dp[i - 1] + tmp;
        }
        return dp[length - 1];
    }

    public int numDecodings(String s) {
        int n = s.length();
        int[] dp = new int[n];
        if(n == 0 || s.charAt(0) == '0') return 0;
        dp[0] = 1;
        for(int i = 1; i < n; i++){
            if(s.charAt(i) == '0'){
                if(s.charAt(i - 1) == '0' || s.charAt(i - 1) > '2'){  // case 2:
                    return 0;
                }else{ // case 1:
                    if(i > 1){
                        dp[i] = dp[i - 2];
                    }else{
                        dp[i] = 1;
                    }
                }
            }else if((s.charAt(i) <= '6' && s.charAt(i) >= '1' && s.charAt(i - 1) == '2') || s.charAt(i - 1) == '1'){ // case 3:
                if(i > 1){
                    dp[i] = dp[i - 1] + dp[i - 2];
                }else{
                    dp[i] = dp[i - 1] + 1;
                }
            }else{ // case 4:
                dp[i] = dp[i - 1];
            }
        }
        return dp[n - 1];
    }
}
